<template>
    <div class="newFriendContainer">
        <el-card class="searchCard">
            <el-input
                v-model="searchUsername"
                class="searchInput"
                placeholder="请输入要查找的账号"
            ></el-input>
            <el-button class="searchBtn" type="primary" @click="searchUser">查找账号</el-button>
        </el-card>
        <p class="newTitle">申请记录</p>
        <el-card class="requireCard" v-if="requireList?.length > 0">
            <template v-for="item in requireList" :key="item.friendshipId">
                <div class="requireItem" @click="handleCheckFriend(item.friendId)">
                    <div class="leftContent">
                        <img class="friendAvatar" :src="item.friendAvatar" />
                        <div class="friendName">
                            <span>{{ item.friendRealname }}</span>
                            <span>{{ item.friendUsername }}</span>
                        </div>
                    </div>
                    <div class="rightContent">
                        <el-icon v-if="item.initiator === userStore.userId">
                            <TopRight />
                        </el-icon>
                        <div
                            :class="[
                                'statusBtn',
                                item.status === 'accept' ? 'accept' : '',
                                item.status === 'verifying' ? 'verifying' : '',
                                item.status === 'refuse' ? 'refuse' : '',
                            ]"
                        >
                            {{ setStatus(item.status) }}
                        </div>
                    </div>
                </div>
            </template>
        </el-card>
        <el-dialog class="detailDialog" v-model="dialogVisiable" align-center width="500">
            <template #header>申请记录详情</template>
            <template #default>
                <div class="dialogContent">
                    <img class="dialogImg" :src="chooseItem?.friendAvatar" alt="" />
                    <span class="dialogUsername">账号：{{ chooseItem?.friendUsername }}</span>
                    <span class="dialogTitle">昵称：{{ chooseItem?.friendRealname }}</span>
                    <span class="dialogInitiator">
                        发起者：{{
                            chooseItem?.initiator === userStore.userId
                                ? `${userStore.realname}`
                                : `${chooseItem?.friendRealname}`
                        }}
                    </span>
                </div>
                <div
                    class="verifyBtn"
                    v-if="
                        chooseItem?.initiator !== userStore.userId &&
                        chooseItem?.status === 'verifying'
                    "
                >
                    <el-button type="primary" @click="handleAgree(chooseItem)">同意</el-button>
                    <el-button type="danger" @click="handleRefuse(chooseItem)">拒绝</el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog class="searchDialog" v-model="searchVisiable" align-center width="500">
            <template #header>已为您查找到对应账户</template>
            <template #default>
                <div class="searchUser">
                    <FriendInfo :showType="3" :showInfo="userMessage"></FriendInfo>
                </div>
                <div class="statusBox" v-if="!contactStatus?.isContact">
                    <el-button
                        type="primary"
                        v-if="userMessage.userId !== userStore.userId"
                        @click="handleApply()"
                    >
                        申请好友
                    </el-button>
                </div>
                <div class="statusBox" v-if="contactStatus?.isContact">
                    <div
                        :class="[
                            'statusBtn',
                            contactStatus.status === 'accept' ? 'accept' : '',
                            contactStatus.status === 'verifying' ? 'verifying' : '',
                            contactStatus.status === 'refuse' ? 'refuse' : '',
                        ]"
                    >
                        {{ setStatus(contactStatus.status) }}
                    </div>
                    <el-button
                        v-if="contactStatus.status === 'refuse'"
                        type="primary"
                        @click="handleApply()"
                    >
                        重新申请好友
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { TopRight } from '@element-plus/icons-vue'
import type { userInfo } from '@/api/user/type'
import {
    reqGetFriendRequire,
    reqVerifyRequire,
    reqSearchUser,
    reqUserFriends,
    reqApplyFriend,
    reqChatHistory,
} from '@/api/messages'
import type {
    FriendRequireItem,
    VerifyFormData,
    ContactStatus,
    userFriendsResponseData,
    ApplyFormData,
    chatHistoryResponseData,
} from '@/api/messages/type'
import { ref, onMounted, watch } from 'vue'
import useUserStore from '@/store/modules/user'
import useMessagesStore from '@/store/modules/messages'
import useWebSocketStore from '@/store/modules/wschat'
import { ElMessage, ElNotification } from 'element-plus'
import { RouteRecordRaw, useRouter } from 'vue-router'

const router = useRouter()
const userStore = useUserStore()
const messagesStore = useMessagesStore()
const webSocketStore = useWebSocketStore()
// 查找的好友账号
const searchUsername = ref<string>('')
// 好友验证列表
const requireList = ref<FriendRequireItem[]>([])
// 查看申请dialog
const dialogVisiable = ref<boolean>(false)
// 查找用户dialog
const searchVisiable = ref<boolean>(false)
// 选择的验证好友
const chooseItem = ref<FriendRequireItem | null>(null)
// 设置好友状态请求体
const verifyForm = ref<VerifyFormData>({
    friendshipId: -1,
    newStatus: '',
    userId: userStore.userId,
    friendId: -1,
})
// 查找到的好友的信息
const userMessage = ref<userInfo>({
    userId: -1,
    username: '',
    avatar: '',
    realname: '',
    description: '',
})
// 查找的用户与本用户的关系状态
const contactStatus = ref<ContactStatus>()
// 发起好友请求的请求体
const applyForm = ref<ApplyFormData>({
    smallId: -1,
    bigId: -1,
    initiator: -1,
    createTime: Date.now(),
})

// 查找好友
const searchUser = async () => {
    const userData = await reqSearchUser({
        userId: userStore.userId,
        searchUsername: searchUsername.value,
    })
    if (userData.data) {
        userMessage.value = userData.data.userInfo
        searchVisiable.value = true
        contactStatus.value = userData.data.contactStatus
    } else if (!userData.data) {
        ElMessage.error(userData.message)
        contactStatus.value = undefined
    }
}

// 申请好友
const handleApply = async () => {
    if (userMessage.value?.userId > userStore.userId) {
        applyForm.value.bigId = userMessage.value.userId
        applyForm.value.smallId = userStore.userId
    } else {
        applyForm.value.bigId = userStore.userId
        applyForm.value.smallId = userMessage.value.userId
    }

    applyForm.value.initiator = userStore.userId

    const applyResult = await reqApplyFriend(applyForm.value)
    if (applyResult.code === 200) {
        ElMessage.success('好友申请发送成功')
    } else {
        ElMessage.error(applyResult.message) //好友申请发送失败
    }

    searchVisiable.value = false
    searchUsername.value = ''
    const friendRequireResData = await reqGetFriendRequire()
    webSocketStore.sendMessage({
        message_type: 'apply',
        sender_id: userStore.userId,
        receiver_id: userMessage.value.userId,
    })
    requireList.value = friendRequireResData.data
}

// 设置好友状态
const setStatus = (status: 'accept' | 'verifying' | 'refuse') => {
    switch (status) {
        case 'accept':
            return '已添加'
        case 'verifying':
            return '等待验证'
        case 'refuse':
            return '已拒绝'
        default:
            return ''
    }
}

// 点击申请记录查看详情
const handleCheckFriend = (friendId: number) => {
    requireList.value?.forEach((item) => {
        if (item.friendId === friendId) {
            chooseItem.value = item
        }
    })
    dialogVisiable.value = true
}

// 重新获取好友列表
const getNewFriendList = async (chooseFriend: FriendRequireItem) => {
    const userFriends: userFriendsResponseData = await reqUserFriends()
    userStore.friends = userFriends.data
    const friendshipRoute: RouteRecordRaw = {
        path: `/contacts/friendship/${chooseFriend.friendId}`,
        component: () => import('@/views/friendship/index.vue'),
        meta: {
            userId: chooseFriend.friendId, //好友id
            username: chooseFriend.friendUsername, //好友用户名
            title: chooseFriend.friendRealname, //菜单标题，即好友名称
            avatar: chooseFriend.friendAvatar, //头像
            hidden: false, //代表路由标题在菜单中是否隐藏
        },
    }
    userStore.menuRoutes[1].children![0].children!.push(friendshipRoute)
    router.addRoute('ContactsDefault', friendshipRoute)
}

// 同意好友申请
const handleAgree = async (chooseFriend: FriendRequireItem) => {
    verifyForm.value.friendshipId = chooseFriend.friendshipId
    verifyForm.value.friendId = chooseFriend.friendId
    verifyForm.value.newStatus = 'accept'
    const requireRes = await reqVerifyRequire(verifyForm.value)
    if (requireRes.code === 200) {
        const myMessage = {
            friendshipId: chooseFriend.friendshipId,
            status: 'accept',
            initiator: chooseFriend.initiator,
            friendId: userStore.userId,
            friendAvatar: userStore.avatar,
            friendUsername: userStore.username,
            friendRealname: userStore.realname,
        }
        webSocketStore.sendMessage({
            message_type: 'verify-require',
            sender_id: userStore.userId,
            receiver_id: chooseFriend.friendId,
            newFriend: myMessage,
        })
        const friendRequireResData = await reqGetFriendRequire()
        requireList.value = friendRequireResData.data
        await getNewFriendList(chooseFriend)
        const newConversations: chatHistoryResponseData = await reqChatHistory()
        messagesStore.conversations = newConversations.data
    }
    dialogVisiable.value = false
}

// 拒绝好友申请
const handleRefuse = async (chooseFriend: FriendRequireItem) => {
    verifyForm.value.friendshipId = chooseFriend.friendshipId
    verifyForm.value.friendId = chooseFriend.friendId
    verifyForm.value.newStatus = 'refuse'
    const requireRes = await reqVerifyRequire(verifyForm.value)
    if (requireRes.code === 200) {
        const myMessage = {
            friendshipId: chooseFriend.friendshipId,
            status: 'refuse',
            initiator: chooseFriend.initiator,
            friendId: userStore.userId,
            friendAvatar: userStore.avatar,
            friendUsername: userStore.username,
            friendRealname: userStore.realname,
        }
        webSocketStore.sendMessage({
            message_type: 'verify-require',
            sender_id: userStore.userId,
            receiver_id: chooseFriend.friendId,
            newFriend: myMessage,
        })
        const friendRequireResData = await reqGetFriendRequire()
        requireList.value = friendRequireResData.data
    }
    dialogVisiable.value = false
}

watch(
    () => webSocketStore.friendApply,
    async (newVal) => {
        if (newVal) {
            ElNotification('收到新的好友申请')
            const friendRequireResData = await reqGetFriendRequire()
            requireList.value = friendRequireResData.data
            webSocketStore.friendApply = false
        }
    },
)

watch(
    () => webSocketStore.newFriend,
    async () => {
        ElNotification(`用户${webSocketStore.newFriend?.friendUsername}已验证了好友申请`)
        const friendRequireResData = await reqGetFriendRequire()
        requireList.value = friendRequireResData.data
        if (webSocketStore.newFriend?.status === 'accept') {
            await getNewFriendList(webSocketStore.newFriend as FriendRequireItem)
            const newConversations: chatHistoryResponseData = await reqChatHistory()
            messagesStore.conversations = newConversations.data
        }
    },
)

onMounted(async () => {
    const friendRequireResData = await reqGetFriendRequire()
    requireList.value = friendRequireResData.data
})
</script>

<style scoped lang="scss">
.newFriendContainer {
    width: 100%;
    height: 100%;
    overflow-y: auto;

    .searchCard {
        width: 100%;
        height: fit-content;

        .searchInput {
            width: 50%;
        }

        .searchBtn {
            margin-left: 10px;
        }
    }

    .newTitle {
        font-size: 24px;
        width: 100%;
        height: 50px;
        line-height: 50px;
        padding: 0 20px;
    }

    .requireCard {
        .requireItem {
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: 100%;
            height: 60px;
            border-bottom: 1px solid #aaaaaa;
            cursor: pointer;

            .leftContent {
                display: flex;

                .friendAvatar {
                    width: 40px;
                    height: 40px;
                    border-radius: 5px;
                }

                .friendName {
                    width: 300px;
                    display: flex;
                    flex-direction: column;
                    justify-content: space-between;
                    margin-left: 20px;
                }
            }

            .rightContent {
                display: flex;
                align-items: center;
            }
        }
    }

    .detailDialog {
        .dialogContent {
            height: 100px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .dialogImg {
            width: 50px;
            height: 50px;
            border-radius: 5px;
        }

        .dialogUsername {
            text-align: center;
            width: fit-content;
            margin-left: 20px;
        }

        .dialogTitle {
            margin-left: 20px;
        }

        .dialogInitiator {
            margin-left: 20px;
        }

        .verifyBtn {
            display: flex;
            justify-content: center;
        }
    }

    .searchDialog {
        .searchUser {
            width: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .statusBox {
            width: 100%;
            margin-top: 20px;
            display: flex;
            justify-content: center;
            gap: 10px;
        }
    }
}

.statusBtn {
    text-align: center;
    color: white;
    width: 80px;
    height: 30px;
    line-height: 30px;
    margin-left: 20px;
    border: 1px solid #aaaaaa;
    border-radius: 5px;
}

.accept {
    background-color: rgb(117, 181, 67);
}

.verifying {
    background-color: gray;
}

.refuse {
    background-color: rgb(250, 76, 76);
}
</style>
